<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <el-row class="break" v-show="rowTagId">
          <el-breadcrumb separator="/">
          <el-breadcrumb-item >学科管理</el-breadcrumb-item>
          <el-breadcrumb-item class="subjectName" :to="{ path: '/subjects/list' }">{{rowtagName}}</el-breadcrumb-item>
          <el-breadcrumb-item>目录管理</el-breadcrumb-item>
        </el-breadcrumb>
        </el-row>
        <el-row >
          <el-col :span="18" >
            <el-form :inline="true" :model="nodeData" class="demo-form-inline">
              <el-form-item :label="$t('table.tagName')">
                <el-input size="small" v-model="tagNames"></el-input>
              </el-form-item>
              <el-form-item :label="$t('table.state')">
                <el-select size="small" v-model="states" placeholder="请选择">
                  <el-option
                    :label="$t('table.prohibit')"
                    value="0"
                  ></el-option>
                  <el-option
                    :label="$t('table.startUsing')"
                    value="1"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button size="small" @click="removeClick">{{
                  $t("table.eliminate")
                }}</el-button>
                <!-- 搜索 -->
                <el-button size="small" type="primary" @click="onSubmit">{{
                  $t("table.search")
                }}</el-button>
              </el-form-item>
            </el-form>
            <div class="grid-content bg-purple"></div
          ></el-col>
          <el-col :span="6" class="right">
            <!-- <i  size="small" v-show="rowTagId"></i> -->
            <el-button
              size="small"
              class="el-icon-back"
              type="text"
              @click="$router.push('/subjects/list')"
              v-show="rowTagId"
              >{{ $t("table.subject") }}</el-button
            >
            <!-- Excel导出 -->
            <el-button size="small" type="primary" @click="handleExcelExport">
              {{ $t("table." + "Excel-Export") }}
            </el-button>
            <!-- 新增用户 -->
            <el-button
              size="small"
              type="success"
              icon="el-icon-edit"
              class="el-btn"
              @click="addAdmin"
              >{{ $t("table.addUser") }}</el-button
            >
            <div class="grid-content bg-purple"></div
          ></el-col>
        </el-row>
        <!-- 消息提示 -->
        <el-alert :title="titleShow" type="info" show-icon> </el-alert>
        <!-- 表格 -->
        <el-table
          class="box"
          :data="tableData"
          style="width: 100%; margin-top: 20px"
          :header-cell-style="tabelStyle"
        >
          <el-table-column
            fixed
            prop="date"
            :label="$t('table.id')"
            type="index"
            width="100"
            :index="indexMethod"
          >
            <!-- :label="$('table.subject')" -->
          </el-table-column>
          <el-table-column prop="subjectName" :label="$t('table.subject')">
          </el-table-column>
          <el-table-column prop="tagName" :label="$t('table.tagName')">
          </el-table-column>
          <el-table-column prop="username" :label="$t('table.creator')">
          </el-table-column>
          <el-table-column prop="addDate" :label="$t('table.dateCreated')">
            <template #default="{ row }">
              {{ formateTime(row.addDate) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="state"
            :label="$t('table.state')"
            :formatter="formatEmployment"
          >
            <!-- 状态是0或者1 -->
          </el-table-column>
          <el-table-column fixed="right" :label="$t('table.state')">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="jinyong(scope.row.id)"
                >{{
                  scope.row.state === 0
                    ? $t("table.startUsing")
                    : $t("table.prohibit")
                }}</el-button
              >
              <el-button
                type="text"
                size="small"
                :disabled="scope.row.state === 1"
                @click="edit(scope.row.id)"
                >{{ $t("table.amend") }}</el-button
              >
              <el-button
                type="text"
                size="small"
                :disabled="scope.row.state === 1"
                @click="del(scope.row.id)"
                >{{ $t("table.delete") }}</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <!-- current-page表示的当前页 -->
        <!-- page-sizes:供我们下拉选择的页容量 -->
        <!-- pagesize:表示当前页容量（一般和page-sizes数组中的第一个值是对应的） -->
        <!-- layout：表示分页的样式展示 -->
        <!-- total表示的是一共有多少条数据 -->
        <!-- @size-change：当每页页容量发生变化时触发 -->
        <!-- @current-change ：页码发生变化时触发 -->
        <div
          class="block"
          style="
            height: 40px;
            margin-top: 30px;
            display: flex;
            justify-content: flex-end;
          "
        >
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-sizes="[5, 10, 15, 20]"
            layout="  prev, pager, next,sizes, jumper"
            :page-size="100"
            :total="total"
          >
          </el-pagination>
        </div>
      </el-card>
      <tags-add
        :rowtagName="rowtagName"
        :dialogVisible.sync="dialogVisible"
        :title="title"
        ref="tagsEdit"
        v-loading="loading"
        :rowTagId="rowTagId"
      ></tags-add>
    </div>
  </div>
</template>

<script>
import {
  list as listDataApi,
  detail,
  remove,
  changeState
} from '@/api/hmmm/tags'
import { status } from '@/api/hmmm/constants' // 枚举文件
import dayjs from 'dayjs'
import tagsAdd from '@/module-hmmm/components/tags-add.vue'
import { handleDownload } from '@/utils/excelExport'

export default {
  name: 'tags',
  components: {
    tagsAdd
  },
  data () {
    return {
      dialogVisible: false,
      total: 0, // 总条数
      page: 1, // 当前页
      pagesize: 5, // 每页多少条
      formInline: {
        user: '',
        region: ''
      },
      tableData: [], // 全部数据
      title: '',
      nodeData: {
        tagName: '',
        state: ''
      },
      editID: '',
      loading: false,
      tagNames: '',
      states: ''
    }
  },
  computed: {
    // 弹出信息
    titleShow () {
      return `数据一共${this.total}条`
    },
    rowTagId () {
      // this.push(`/你的地址?id=${学科id}`)
      return this.$route.query.id ? this.$route.query.id : null
    },
    rowtagName () {
      return this.$route.query.name ? this.$route.query.name : null
    }
  },
  created () {
    this.listData()
  },
  methods: {
    // excel导出。
    async handleExcelExport () {
      const {
        data: { items }
      } = await listDataApi({ page: 1, pagesize: 9999 })
      const tableTypeList = {
        id: '序号',
        subjectName: '学科',
        tagName: '标签名',
        username: '创建者',
        addDate: '录入时间',
        state: '状态'
      }
      const zh = []
      const type = {}
      for (const k in tableTypeList) {
        zh.push(tableTypeList[k])
        const typeKey = tableTypeList[k]
        type[typeKey] = k
      }
      handleDownload(items, zh, type)
    },
    // table标头样式
    tabelStyle () {
      return {
        'border-bottom': '2px solid #e8e8e8',
        color: '#909399',
        backgroundColor: '#f4f4f4'
      }
    },

    // 清除
    removeClick () {
      this.tagNames = ''
      this.states = ''
    },
    // 搜索
    async onSubmit () {
      // console.log(this.nodeData)
      const { data } = await listDataApi({
        page: this.page,
        pagesize: this.pagesize,
        tagName: this.tagNames || null,
        state: this.states || null,
        subjectID: this.rowTagId || null
      })
      // console.log(data)
      this.tableData = data.items
    },
    // 禁用按鈕
    async jinyong (id) {
      const rowObj = this.tableData.find((item) => item.id === id)

      rowObj.state = rowObj.state === 1 ? 0 : 1
      const { data: potsData } = await detail({ id: id })
      this.potsData = potsData
      // 按钮状态
      await changeState({ id: id, state: rowObj.state })
    },

    // 修改
    async edit (id) {
      this.loading = true
      const data = { id }
      this.title = '修改目录'
      const { data: a } = await detail(data)
      const res = {
        id,
        subjectID: a.subjectID,
        tagName: a.tagName
      }
      this.editID = a.id // 修改才有id
      this.nodeData = res
      this.dialogVisible = true // 先让数据请求到了，才弹出框，不让数据不渲染
      this.loading = false
    },
    // 刪除
    del (id) {
      const data = { id }
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {})
        .then(async () => {
          await remove(data)
          this.$message.success('删除成功!') // 弹出提示
          this.listData()
        })
        .catch(() => {})
    },
    // 点击新增
    addAdmin () {
      this.title = '新增目录'
      this.dialogVisible = true
    },
    // tabol格式化信息 状态是0或者1
    formatEmployment (row, column, cellValue, index) {
      // 拿当前的返回值跟枚举的value比较拿到比较的结果
      const obj = status.find((item) => item.value === cellValue)
      return obj.label
    },
    // 时间格式修改
    formateTime (time) {
      // 拿到了时间修改格式
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    async listData () {
      const { data } = await listDataApi({
        page: this.page,
        pagesize: this.pagesize,
        subjectID: this.rowTagId
      })

      this.tableData = data.items
      this.total = data.counts // 总数
    },
    // 计算索引
    indexMethod (index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 分页
    // 条数改变触发
    handleSizeChange (val) {
      this.pagesize = val
      this.page = 1 // 页容量每次发生变化都回到第一页重新开始
      this.listData()
    },
    // 翻页改变触发
    handleCurrentChange (val) {
      this.page = val
      this.listData()
    }
  }
}
</script>

<style scoped>
.el-icon-back {
  color: #66b1ff;
  height: 100%;
}
::v-deep .el-icon-back:before {
  margin-right: 7px;
}
.break{
  height: 30px;
  line-height: 30px;
  border-bottom: 1px solid #EBEEF5;
  margin-bottom: 20px;
}
.right{
  display: flex;
  justify-content: flex-end;
}
</style>
